package com.atguigu.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.cart.feign.ProductFeignService;
import com.atguigu.gulimall.cart.interceptor.CartInterceptor;
import com.atguigu.gulimall.cart.service.CartService;
import com.atguigu.gulimall.cart.vo.Cart;
import com.atguigu.gulimall.cart.vo.CartItem;
import com.atguigu.gulimall.cart.vo.SkuInfoVo;
import com.atguigu.gulimall.cart.vo.UserInfTo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CartServiceImpl implements CartService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private ThreadPoolExecutor executor;

    private final String CART_PREFIX = "gulimall:cart";

    @Override
    public CartItem addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        //1 获取购物车
        BoundHashOperations<String, Object, Object> operations = getCartOps();
        String res = (String) operations.get(skuId.toString());
        if (StringUtils.isEmpty(res)) {
            CartItem cartItem = new CartItem();
            //购物车没有此商品
            //2 远程查询商品信息
            CompletableFuture<Void> getSkuInfoTask1 = CompletableFuture.runAsync(() -> {
                R skuInfo = productFeignService.getSkuInfo(skuId);
                SkuInfoVo data = skuInfo.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                });
                cartItem.setCheck(true);
                cartItem.setCount(num);
                cartItem.setImage(data.getSkuDefaultImg());
                cartItem.setTitle(data.getSkuTitle());
                cartItem.setSkuId(skuId);
                cartItem.setPrice(data.getPrice());
            }, executor);

            //2.1 sku的组合信息
            CompletableFuture<Void> getSkuInfoTask2 = CompletableFuture.runAsync(() -> {
                List<String> values = productFeignService.getSkuSaleAttrValues(skuId);
                cartItem.setSkuAttr(values);
            }, executor);

            CompletableFuture.allOf(getSkuInfoTask1, getSkuInfoTask2).get();
            //3 添加或更新商品
            //把对象序列化json
            String jsonString = JSON.toJSONString(cartItem);
            operations.put(skuId.toString(), jsonString);
            return cartItem;
        } else {
            //购物车有此商品，修改数量
            CartItem cartItem = new CartItem();
            cartItem = JSON.parseObject(res, CartItem.class);
            cartItem.setCount(cartItem.getCount() + num);

            String jsonString = JSON.toJSONString(cartItem);
            operations.put(skuId.toString(), jsonString);
            return cartItem;
        }
    }

    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cart = getCartOps();

        Object o = cart.get(skuId.toString());
        CartItem cartItem = JSON.parseObject((String) o, CartItem.class);
        return cartItem;
    }

    /**
     * 获取购物车
     *
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        UserInfTo userInfTo = CartInterceptor.threadLocal.get();
        //1
        String cartKey = "";
        if (userInfTo.getUserId() != null) {
            cartKey = CART_PREFIX + userInfTo.getUserId();
        } else {
            cartKey = CART_PREFIX + userInfTo.getUserKey();
        }
        //2 判断现在添加的商品在购物车是否有一样的
        // 一样 数量相加
        // 获取购物车信息
        BoundHashOperations<String, Object, Object> operations = stringRedisTemplate.boundHashOps(cartKey);
        return operations;
    }

    private void merge(CartItem tempCartItem) {
        //1 获取用户购物车
        BoundHashOperations<String, Object, Object> operations = getCartOps();
        String res = (String) operations.get(tempCartItem.getSkuId().toString());
        if (StringUtils.isEmpty(res)) {
            //购物车没有此商品，添加到用户购物车
            String jsonString = JSON.toJSONString(tempCartItem);
            operations.put(tempCartItem.getSkuId().toString(), jsonString);

        } else {
            //购物车有此商品，修改数量
            CartItem cartItem = new CartItem();
            cartItem = JSON.parseObject(res, CartItem.class);
            cartItem.setCount(cartItem.getCount() + tempCartItem.getCount());

            String jsonString = JSON.toJSONString(cartItem);
            operations.put(tempCartItem.getSkuId().toString(), jsonString);
        }
    }

    @Override
    public Cart getCart() {
        Cart cart = new Cart();

        UserInfTo userInfTo = CartInterceptor.threadLocal.get();
        if (userInfTo.getUserId() != null) {
            //1 登录
            String cartKey = CART_PREFIX + userInfTo.getUserId();
            BoundHashOperations<String, Object, Object> operations =
                    stringRedisTemplate.boundHashOps(cartKey);
            //2 如果有临时购物车 合并
            List<CartItem> tempCartItems = getCartItems(CART_PREFIX + userInfTo.getUserKey());
            List<CartItem> CurrentCartItems = getCartItems(cartKey);
            if (tempCartItems != null && tempCartItems.size() > 0) {
                for (CartItem item : tempCartItems) {
                    merge(item);
                }
                // 清除购物车
                clearCart(CART_PREFIX + userInfTo.getUserKey());
            }

            //3 获取合并后的购物车
            List<CartItem> totalCartItems = getCartItems(cartKey);
            cart.setItems(totalCartItems);
            return cart;
        } else {
            String cartKey = CART_PREFIX + userInfTo.getUserKey();
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);
            return cart;
        }
    }

    private List<CartItem> getCartItems(String cartKey) {
        BoundHashOperations<String, Object, Object> operations =
                stringRedisTemplate.boundHashOps(cartKey);
        List<Object> values = operations.values();
        List<CartItem> cartItems = null;
        if (values != null && values.size() > 0) {
            cartItems = values.stream().map((obj) -> {
                String str = (String) obj;
                CartItem cartItem = JSON.parseObject(str, CartItem.class);
                return cartItem;
            }).collect(Collectors.toList());
            return cartItems;
        }
        return null;
    }

    @Override
    public void clearCart(String cartKey) {
        stringRedisTemplate.delete(cartKey);
    }

    @Override
    public void checkItem(Long skuId, Integer check) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(check == 1 ? true : false);
        String jsonString = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(), jsonString);
    }

    /**
     * 修改购物项数量
     *
     * @param skuId
     * @param num
     * @return
     */
    @Override
    public void changeItemCount(Long skuId, Integer num) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(num);

        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId, JSON.toJSONString(cartItem));
    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    @Override
    public List<CartItem> getUserCartItems() {
        UserInfTo userInfTo = CartInterceptor.threadLocal.get();
        if (userInfTo.getUserId() == null) {
            return null;
        } else {
            String cartKey = CART_PREFIX + userInfTo.getUserId();
            List<CartItem> cartItems = getCartItems(cartKey);
            List<CartItem> collect = cartItems
                    .stream()
                    .filter(item -> item.getCheck())
                    .map(item -> {
                        R price = productFeignService.getPrice(item.getSkuId());
                        String data = (String) price.get("data");
                        item.setPrice(new BigDecimal(data));
                        return item;})
                    .collect(Collectors.toList());
            return collect;
        }
    }
}